import datetime
import os
import sys
from multiprocessing import Process

import psutil
from apscheduler.executors.pool import ProcessPoolExecutor, ThreadPoolExecutor

from config import strategy_config
from service import notify_mail

# print(sys.path)
sys.path.append(strategy_config.python_quant_path)
from python_quant.common.log import get_logger
from li_run import run_strategy
from python_quant.common import global_dicts
from apscheduler.schedulers.blocking import BlockingScheduler

from strategy_module.new_stock_filter_strategy import NewStockFilterStrategy

log = get_logger("li")


def do_select_stock_filter():
    new_stock = NewStockFilterStrategy()
    try:
        stocks = new_stock.do_select()
        notify_mail.send_mail_thread("今日股票池", str(stocks))
    except Exception as result:
        log.error(result)

    try:
        # new_stock.do_update()
        notify_mail.send_mail_thread("股票池支撑压力位更新完毕", "股票池支撑压力位更新完毕")
    except Exception as result:
        log.error(result)


def timer_task():
    executor_process = ProcessPoolExecutor()
    executor_thread_pool = ThreadPoolExecutor()

    executors = {
        'default': executor_process,
        'executor_thread_pool': executor_thread_pool
    }

    scheduler = BlockingScheduler(executors=executors, timezone='Asia/Shanghai')

    scheduler.add_job(do_select_stock_filter, trigger="cron", day_of_week="*", hour=11, minute=51,
                      executor='executor_thread_pool')
    scheduler.add_job(run_strategy, trigger="cron", day_of_week="*", hour=22, minute=9,
                      executor='default')
    scheduler.start()


def while_do_select_stock_filter():
    while True:
        if datetime.datetime.now().strftime("%H:%M:%S") == '22:16:00':
            print("Running do_select_stock_filter")
            do_select_stock_filter()


def while_do_run_strategy():
    while True:
        if datetime.datetime.now().strftime("%S") == '20':
            print("Running do_run_strategy")
            run_strategy()


if __name__ == '__main__':
    print('main process %s.' % os.getpid())
    p = psutil.Process(os.getpid())
    global_dicts._init()
    global_dicts.set_value('main', os.getpid())

    while_do_select_stock_filter_process = Process(target=while_do_select_stock_filter)
    while_do_run_strategy_process = Process(target=while_do_run_strategy)

    while_do_select_stock_filter_process.start()
    while_do_run_strategy_process.start()
    while_do_select_stock_filter_process.join()
    while_do_run_strategy_process.join()

    '''
    while True:
        print(while_do_run_strategy_process.is_alive(), while_do_select_stock_filter_process.is_alive())
        if not while_do_run_strategy_process.is_alive():
            while_do_run_strategy_process.terminate()
            while_do_run_strategy_process = Process(target=while_do_run_strategy)
            while_do_run_strategy_process.start()

        if not while_do_select_stock_filter_process.is_alive():
            while_do_select_stock_filter_process.terminate()
            while_do_select_stock_filter_process = Process(target=while_do_select_stock_filter)
            while_do_select_stock_filter_process.start()

        while_do_select_stock_filter_process.join()
        while_do_run_strategy_process.join()
    '''
